package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.ClazzService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class StudentServiceImpl extends ServiceImpl<StudentMapper, Student> implements StudentService {

    @Autowired
    private ClazzService clazzService;
    @Override
    public PageResult<Student> listStudent(StudentQueryParam student) {
        Page<Student> studentPage=Page.of(student.getPage(),student.getPageSize());
        studentPage= lambdaQuery().like(student.getName()!=null&&!student.getName().isEmpty(),Student::getName,student.getName()    ).
                eq(student.getDegree() != null,Student::getGender,student.getDegree()).
                eq(student.getClazzId() != null ,Student::getClazzId,student.getClazzId()).
                page(studentPage);

        List<Student> students = studentPage.getRecords();
//        班级的id
        List<Integer> clazzId = students.stream().map(s -> s.getClazzId()
        ).collect(Collectors.toList());

        if (clazzId!=null) {
//            班级的全部信息
            List<Clazz> clazzes = clazzService.listByIds(clazzId);

            students.forEach(s -> clazzes.forEach(c -> {
                if (s.getClazzId()!=null&&s.getClazzId().equals(c.getId())){
                    s.setClazzName(c.getName());
                }
            }));

        }

        return new PageResult<>(studentPage.getTotal(),studentPage.getRecords());
    }

    @Override
    public void saveStudent(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());

        save(student);
    }
}
